<?php
// +---------------------------------------------------------------------------------
// | ECODE [ 随心而行 勿忘始终]
// +---------------------------------------------------------------------------------
// | Copyright (c) 2017 ECODE All rights reserved.
// +---------------------------------------------------------------------------------
// | Author: 鬼谷子 <majianwei168@outlook.com>
// +---------------------------------------------------------------------------------
namespace app\admin\controller;
use \think\Controller;
use \think\Db;
class Build extends Base
{


	private $moduleDir;     //模块目录
	private $controllerDir; //控制器目录
	private $logicDir;      //逻辑处理目录
	private $modelDir;      //模型目录
	private $validateDir;      //模型目录
	private $viewDir;       //视图目录
	private $phpTemp;       //生成模板目录
	private $suffix;        //生成模板文件后缀
    public function _initialize() 
    {

    	parent::_initialize();
    	
    	$this->moduleDir 		= ROOT_PATH . 'application' . DS . 'admin' . DS;
    	$this->controllerDir 	= $this->moduleDir . 'controller' . DS;
    	$this->logicDir			= $this->moduleDir . 'logic' . DS;
    	$this->modelDir 		= $this->moduleDir . 'model' . DS;
    	$this->validateDir		= $this->moduleDir . 'validate' . DS;
    	$this->viewDir			= $this->moduleDir . 'view' . DS;
    	$this->phpTemp			= $this->controllerDir . 'buildtmp' . DS;
    	$this->suffix			= '.temp';

    }
	public function index()
	{
		echo 'build apping ...';
	}

	//创建模型
	public function createModel()
	{
	/**
	 * id 默认自动创建ID为主键并设置为表单隐藏域
	 * create_time update_time is_delete 默认有的三个字段
	 * 删除都为软删除
	 */
		if( $this->isPost() ) {
			//接收数据
			$data = input();
			$tab  		= $data ['tab_name'];
			$menuName  	= $data ['function_title'];
		
			$this->buildTab($data);
			$this->controllerTmp($tab);
			$this->logicTmp($tab);
			$this->modelTmp($tab);
			$this->validateTmp($tab);
			$this->htmlEditTpl($tab, $data);
			$this->htmlListTpl($tab, $data);
			$modelUrl = $tab . '/index';
			echo '<a href="'.url($modelUrl).'">'.$menuName.'</a>';
		} else {
			return view();
		}
		
	}

	//增加模型字段及表单规则
	public function addFieldRule()
	{}

	//创建模型记录
	public function modelLog()
	{}

	/**
	 * 后期优化：增加表引擎选择，默认让字段集设制为utf8
	 */
	//创建数据结构
	protected function buildTab($data)
	{	
		//变量定义
		$fix 			= config('database.prefix');
		$tabName 		= $fix.$data['tab_name'];
		$functionName 	= $data['function_title'];
		unset($data['tab_name'],$data['function_title']);

		//整理数据
		$sqlArr = array();
		foreach ($data as $key => $value) {
			foreach ($value as $k => $v) {
				 $sqlArr[$k][$key] = $v;
			}
		}

		//合成SQL语句
		$sql 		= '';
		$sqlStart 	= "create table {$tabName}( id INT NOT NULL AUTO_INCREMENT, create_time INT NOT NULL,update_time INT NOT NULL, is_delete INT(1) NOT NULL default 1 ,";
		$sqlEnd 	= 'PRIMARY KEY ( id ));';
		$isNull 	= array(0=>'NOT NULL', 1=>'NULL');
		foreach ($sqlArr as $key => $value) {
			//如果没有定义，则为 NOT NULL
			if(!isset($value ['field_null'])) {
				$value ['field_null'] = 0;
			}
			$sql .= "{$value ['field_name']} {$value ['field_type']}({$value ['field_length']}) {$isNull[$value ['field_null']]}  COMMENT '{$value ['field_desc']}',";
		}
		$sql = $sqlStart . $sql . $sqlEnd;
		$res = Db::execute($sql);
		echo '数据库结构生成成功<br>';
		//执行SQL 
	}

	//生成控制器、逻辑层控制、模型层、验证层| 及模板目录、模板文件(编辑|列表)
	protected function buildTmp()
	{

	}
	//控制器模板
	private function controllerTmp($name)
	{
		$name 			= ucfirst($name);
		$tmpFile 		= $this->phpTemp . 'controller' . $this->suffix;
		$fileStr        = file_get_contents($tmpFile);
		$fileNewStr     = str_replace('({$name})', $name, $fileStr);
		$fileName       = $this->controllerDir . $name.'.php';
		$res = file_put_contents($fileName, $fileNewStr);
		if($res) {
			echo $fileName . ' ... 成功<br>';
		} else {
			echo $fileName . ' ... 失败！！<br>';
		}

	}
	//逻辑层模板
	private function logicTmp($name)
	{
		$name 			= ucfirst($name);
		$tmpFile 		= $this->phpTemp . 'logic' . $this->suffix;
		$fileStr        = file_get_contents($tmpFile);
		$fileNewStr     = str_replace('({$name})', $name, $fileStr);
		$fileName       = $this->logicDir . $name.'.php';
		$res = file_put_contents($fileName, $fileNewStr);
		if($res) {
			echo $fileName . ' ... 成功<br>';
		} else {
			echo $fileName . ' ... 失败！！<br>';
		}
	}
	//模型层模板
	private function modelTmp($name)
	{
		$name 			= ucfirst($name);
		$tmpFile 		= $this->phpTemp . 'model' . $this->suffix;
		$fileStr        = file_get_contents($tmpFile);
		$fileNewStr     = str_replace('({$name})', $name, $fileStr);
		$fileName       = $this->modelDir . $name.'.php';
		$res = file_put_contents($fileName, $fileNewStr);
		if($res) {
			echo $fileName . ' ... 成功<br>';
		} else {
			echo $fileName . ' ... 失败！！<br>';
		}
	}
	//验证层模板
	private function validateTmp($name)
	{
		$name 			= ucfirst($name);
		$tmpFile 		= $this->phpTemp . 'validate' . $this->suffix;
		$fileStr        = file_get_contents($tmpFile);
		$fileNewStr     = str_replace('({$name})', $name, $fileStr);
		$fileName       = $this->validateDir . $name.'.php';
		$res = file_put_contents($fileName, $fileNewStr);
		if($res) {
			echo $fileName . ' ... 成功<br>';
		} else {
			echo $fileName . ' ... 失败！！<br>';
		}
	}
	/**
	 * 生成编辑视图
	 * @author   鬼谷子<majianwei168@outlook.com>
	 * @DateTime 2017-02-23T20:58:48+0800
	 * @param  string $tab  表名
	 * @param  array $data  字段、标题、控件类型 eg: array(array('field' => 'title', 'form_type' => 'text', 'label' => '标题'))
	 * @return   [type]                              [description]
	 */
	private function htmlEditTpl($tab, $data)
	{
		$data = $this->collectData($data);
		
		$widgetStr      = '';
		$mailTmpFile 	= $this->phpTemp . 'editmain' . $this->suffix;
		$search  = array('{($field)}', '{($title)}');
		foreach ($data ['field'] as $key => $value) {
			$file 		= $this->phpTemp . $value['form_type'] . $this->suffix;
			$str 		= file_get_contents($file);
			$replace 	= array($value['field_name'], $value['from_title']);
			//控件标题和表单name替换对应
			$newStr     = str_replace($search, $replace, $str);
			$widgetStr .= $newStr;
		}
		//合成一个HTML模板文件
		$editmainStr    = file_get_contents($mailTmpFile);
		$newTpl 		= str_replace('({$content})', $widgetStr, $editmainStr);
		
		//创建对应的文件夹及文件
		$newTplDir  = $this->viewDir . $tab;
		//判断是有已经有文件夹
		if(!is_dir($newTplDir)) {
			mkdir($newTplDir);
		}
		//判断是否有创建权限
		$fileName 	= $newTplDir . DS . 'edit.html';
		$res = file_put_contents($fileName, $newTpl);
		if($res) {
			echo $fileName . '...成功<br>';
		} else {
			echo $fileName . '...失败！！<br>';
		}
	}
	/**
	 * 生成列表视图
	 * @author 鬼谷子<majianwei168@outlook.com>
	 * @DateTime 2017-02-23T22:59:34+0800
	 * @param    string                   $tab  表名
	 * @param    array                   $data  
	 * @return   [type]                         [description]
	 */
	private function htmlListTpl($tab, $data)
	{

		$data 	= $this->collectData($data);
		$field 	= $data ['field'];

		$th     = '';
		$td 	= '';
		foreach ($field as $key => $value) {
			$th .= '<th>' .$value['from_title']. '</th>';
			$td .= '<td>{$vo.'.$value['field_name'].'}</td>';
		}
		$tmpFile 		= $this->phpTemp . 'listmain' . $this->suffix;
		$fileStr        = file_get_contents($tmpFile);

		$search  = array('({$th})', '({$td})');
		$replace = array($th, $td);
		$fileNewStr     = str_replace($search, $replace, $fileStr);
		//$fileName       = $this->viewDir .'index.html';
		//创建对应的文件夹及文件
		$newTplDir  = $this->viewDir . $tab;
		//判断是有已经有文件夹
		if(!is_dir($newTplDir)) {
			mkdir($newTplDir);
		}
		$fileName 	= $newTplDir . DS . 'index.html';

		$res = file_put_contents($fileName, $fileNewStr);
		if($res) {
			echo $fileName . '...成功<br>';
		} else {
			echo $fileName . '...失败！！<br>';
		}

	}
	/**
	 * 数据整理
	 * @author 鬼谷子<majianwei168@outlook.com>
	 * @DateTime 2017-02-23T21:54:57+0800
	 * @param    array                   $data  原数据
	 * @return   array                         
	 */
	private function collectData($data)
	{
		$newArr ['tab'] 		= $data ['tab_name'];
		$newArr ['menu_title'] 	= $data ['function_title'];
		unset($data ['tab_name'],$data ['function_title']);
		//整理数据
		foreach ($data as $key => $value) {
			foreach ($value as $k => $v) {
				 $newArr['field'][$k][$key] = $v;
			}
		}
		return $newArr;
	}
}